'''
Created on 2014. 1. 3.

@author: jhpark
'''
import os

workdir = os.path.dirname(__file__)

uifiles = os.listdir(os.path.join(workdir,  'design'))
os.chdir(workdir)

def get_class_name(file_path):
    fdata = open(file_path)
    className = ''
    baseClassName = ''
    
    for lineTxt in fdata:
        lineTxt.strip()
        if len(lineTxt.split(' ')) > 1:
            head_word = lineTxt.split(' ')[0]
            other_word = lineTxt.split(' ')[1]
        if head_word == 'class':
            className = other_word.split('(')[0]
            break
    
    for lineTxt in fdata:
        lineTxt.strip()
        baseClassName = ''
        
        if len(lineTxt.split(' = ')) > 1:
            baseClassName = lineTxt.split(' = ')[1]
            
        if baseClassName == '':
            continue
              
        if baseClassName == 'QtGui.QMainWindow()\n':
            baseClassName = 'QtGui.QMainWindow'
            break
        elif baseClassName == 'QtGui.QWidget()\n':
            baseClassName = 'QtGui.QWidget'
            break
        elif baseClassName == 'QtGui.QDialog()\n':
            baseClassName = 'QtGui.QDialog'
            break

    fdata.close()
    return className, baseClassName
        
#convert .ui file to .py file and compile .py files
for ui in uifiles:
    file_name = ui.split('.')[0]
    ext_name = ui.split('.')[1]
    dst_path = file_name + '.py'
     
    if file_name == '__init__.py' or ext_name == 'ui':
        continue
    
    work_dir_cls_name = file_name.split('_')[1]
    
    if os.path.exists(work_dir_cls_name + '.py'):
        continue
    
    #write file 
    class_name, base_name = get_class_name('design\\' + dst_path)
    
    qtWindowFile = file(work_dir_cls_name + '.py', 'w')
    sourceTxt = ['from PyQt4 import QtGui\n',
                 'from design.' + file_name + ' import ' + class_name + '\n\n',
                 'class ' + work_dir_cls_name + '(' + base_name + '):\n',
                 '\tdef __init__(self, parent = None):\n',
                 '\t\t' + base_name + '.__init__(self, parent)\n',
                 '\t\tself.ui = ' + class_name + '()\n',
                 '\t\tself.ui.setupUi(self)\n']
    
    qtWindowFile.writelines(sourceTxt)
    qtWindowFile.close()

    
